import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:share_fit/app/controllers/device/dail/dial_logic.dart';
import 'package:share_fit/app/controllers/device/dail/dial_model.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/tools/color_const.dart';
import 'package:share_fit/app/tools/locale_tool.dart';
import 'package:share_fit/app/tools/log_utils.dart';
import 'package:share_fit/generated/locales.g.dart';

import 'dial_const.dart';

class DialLimitDialog extends Dialog {

  final logic = Get.put(DialLogic());
  final state = Get.find<DialLogic>().state;
  final DialModel dialModel;

  DialLimitDialog(this.dialModel, {super.key});

  @override
  Widget build(BuildContext context) {
    state.uploadFileValue = 0;
    state.uploadFileText = '';
    state.isUploadFile = false;
    state.limitSelectedIndex = 0;
    return GestureDetector( // 点击遮罩层隐藏弹框
        child: Material(
            type: MaterialType.transparency, // 配置透明度
            child: Center(
                child: GestureDetector( // 点击遮罩层关闭弹框，并且点击非遮罩区域禁止关闭
                    onTap: () {
                      logger.d('～');
                    },
                    child: Container(
                        width: 900.w,
                        height: LocaleTool.locale.contains('en')? 1100.h : 900.h,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10),
                          color: Colors.white,
                        ),
                        child: Column(
                            children: [
                              Container(
                                  alignment: Alignment.topCenter,
                                  margin: EdgeInsets.fromLTRB(40.w, 50.h, 40.w, 0),
                                  child: Text(LocaleKeys.dial_max_limit.ts, style: TextStyle(fontSize: 54.sp, color: ColorConst.btnFontColor,))),
                              Container(
                                  alignment: Alignment.topCenter,
                                  margin: EdgeInsets.fromLTRB(40.w, 20.h, 40.w, 0),
                                  child: Text(LocaleKeys.dial_limit_selected.ts, style: TextStyle(fontSize: 46.sp, color: ColorConst.btnFontColor,))),
                              SizedBox(height: 50.h,),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                children: [
                                  Stack(
                                    children: [
                                      GestureDetector(
                                        onTap: (){
                                          logic.updateLimitSelected(1);
                                        },
                                        child: Image(image: NetworkImage(getLimit(0).preview), width: 300.w, height: 300.w,),
                                      ),
                                      GetBuilder<DialLogic>(
                                          id: 'update_limit_selected',
                                          builder: (_){
                                            return Container(
                                              margin: EdgeInsets.only(left: 240.w, bottom: 50.h),
                                              child: Visibility(
                                                visible: state.limitSelectedIndex==1,
                                                replacement: Opacity(opacity: 0.8, child: Image(
                                                  image:const AssetImage('assets/images/device/ic_circle_unchecked.png'),
                                                  width: 50.w, height: 50.w,),),
                                                child: Image(
                                                    image:const AssetImage('assets/images/device/ic_circle_checked.png'),
                                                    width: 50.w, height: 50.w),
                                              ),
                                            );
                                          }),
                                    ],
                                  ),
                                  Stack(
                                    children: [
                                      GestureDetector(
                                        onTap: (){
                                          logic.updateLimitSelected(2);
                                        },
                                        child: Image(image: NetworkImage(getLimit(1).preview), width: 300.w, height: 300.w,),
                                      ),
                                      GetBuilder<DialLogic>(
                                          id: 'update_limit_selected',
                                          builder: (_){
                                            return Container(
                                              margin: EdgeInsets.only(left: 240.w, bottom: 50.h),
                                              child: Visibility(
                                                visible: state.limitSelectedIndex==2,
                                                replacement: Opacity(opacity: 0.8, child: Image(
                                                  image:const AssetImage('assets/images/device/ic_circle_unchecked.png'),
                                                  width: 50.w, height: 50.w,),),
                                                child: Image(
                                                    image:const AssetImage('assets/images/device/ic_circle_checked.png'),
                                                    width: 50.w, height: 50.w),
                                              ),
                                            );
                                          }),
                                    ],
                                  ),
                                ],
                              ),
                              Container(
                                width: 700.w,
                                height: 140.h,
                                margin: EdgeInsets.only(top: 90.h),
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                    color: ColorConst.gray50,
                                    borderRadius: BorderRadius.circular(30)),
                                child: Stack(
                                  children: [
                                    GetBuilder<DialLogic>(
                                        id: DialConst.dialUploadFileViewId,
                                        builder: (_){
                                          return SizedBox(
                                            width: 700.w,
                                            height: 140.h,
                                            child: ClipRRect(
                                              borderRadius: const BorderRadius.all(Radius.circular(100)),
                                              child: LinearProgressIndicator(
                                                value: state.uploadFileValue,
                                                backgroundColor: ColorConst.gray50,
                                                valueColor: AlwaysStoppedAnimation<Color>(ColorConst.accentColor),
                                              ),),);
                                        }),
                                    GestureDetector(
                                      behavior: HitTestBehavior.opaque,
                                      onTap: (){
                                        // if(!state.hasPermisson) {
                                        //   showToast(LocaleKeys.dial_open_permisson.ts);
                                        //   return;
                                        // }

                                        logger.d('index== ${state.limitSelectedIndex}');
                                        if(state.limitSelectedIndex==0) {
                                          return;
                                        }

                                        List<dynamic> watchFaceInfoTemp = [];
                                        for(var info in state.watchFaceInfo) {
                                          Map<dynamic, dynamic> map = jsonDecode(jsonEncode(info));
                                          if((4&map['type'])==4){
                                            watchFaceInfoTemp.add(map);
                                          }
                                        }

                                        Map<dynamic, dynamic> map = jsonDecode(jsonEncode(watchFaceInfoTemp[state.limitSelectedIndex-1]));
                                        logger.d('deleted: /$map/${map['id']}/${map['version']}');
                                        logic.applyWatchFace(map['id'], map['version'], 2).then((value){
                                          logic.download(dialModel.resource).then((value) =>
                                              logic.uploadWatchFace(dialModel.resource).then((value){
                                                bool isSame = false;
                                                List<dynamic> lists = state.downlodLists;
                                                for(var element in lists) {
                                                  DialModel temp = DialModel().fromJson(jsonDecode(element));
                                                  isSame = temp.title == dialModel.title;
                                                  if(temp.title == dialModel.title) {
                                                    isSame = true;
                                                    break;
                                                  }
                                                }

                                                if(!isSame) {
                                                  logic.getWatchFaceInfo().then((value) {
                                                    var info = state.watchFaceInfo[state.watchFaceInfo.length-1];
                                                    Map map = jsonDecode(jsonEncode(info));
                                                    if((4&map['type'])==4){
                                                      dialModel.bleId = '${map['id']}';
                                                    }
                                                    lists.add(dialModel.toJson());
                                                  });
                                                }
                                                Future.delayed(const Duration(seconds: 1), ()=>Navigator.pop(context));
                                              }));
                                        });
                                      },
                                      child: Center(
                                        child: GetBuilder<DialLogic>(
                                          id: DialConst.dialUploadFileTextViewId,
                                          builder: (_){
                                            return Text(state.uploadFileText.isEmpty?LocaleKeys.dial_sync.ts:state.uploadFileText, style: TextStyle(fontSize: 46.sp, color: ColorConst.btnFontColor),);
                                          },
                                        ),
                                      ),),
                                  ],
                                ),
                              ),
                            ]
                        )
                    )
                )
            )
        ),
        onTap: () {
          // Navigator.pop(context);
        }
    );
  }

  getLimit(index) {
    List<String> limitId = [];
    for(var info in state.watchFaceInfo) {
      Map<dynamic, dynamic> map = jsonDecode(jsonEncode(info));
      if((4&map['type'])==4){
        limitId.add(map['id']);
      }
    }
    logger.d('limitIds:$limitId');
    for(var element in state.downlodLists) {
      Map temp = jsonDecode(element);
      if(limitId[index]=='${temp['bleId']}') {
        DialModel dialModel = DialModel().fromJson(temp);
        logger.d('limitId:===>> $index:${limitId[index]}/$dialModel/$temp');
        return dialModel;
      }
    }
    return DialModel().fromJson(jsonDecode(state.downlodLists[0]));
  }

}